package com.xuelang.pipeline.app.pipeline.impl;

import com.xuelang.hiforce.base.cache.client.service.DistributeCacheManager;
import com.xuelang.pipeline.client.common.constant.Constant;
import com.xuelang.pipeline.client.common.result.PageRecord;
import com.xuelang.pipeline.client.common.util.RedisHelper;
import com.xuelang.pipeline.client.pipeline.dto.PipelineInstanceQuery;
import com.xuelang.pipeline.client.pipeline.enums.PipelineInstanceEnum;
import com.xuelang.pipeline.domain.pipeline.PipelineInstance;
import com.xuelang.pipeline.domain.pipeline.service.PipelineInstanceDomainService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author liuyuan.ly
 * @since 2024/7/25 13:51
 */
@Service
@Slf4j
@ConditionalOnProperty(prefix = "scheduling", name = "retry", havingValue = "true")
public class PipelineWorkflowRetryImpl {

    @Autowired
    private PipelineInstanceDomainService pipelineInstanceDomainService;
    @Autowired
    private DistributeCacheManager redisHelper;

    @Scheduled(cron = "${devops.track.workflow:0 */10 * * * ?}")
    public void retryTrackPipelineInstance() {
        log.info("retry track .....");
        // 重试最多 2次流水线实例 每10分钟一次
        PipelineInstanceQuery query = new PipelineInstanceQuery();
        query.setPipelineStatus(PipelineInstanceEnum.running.getKey());
        query.setStartTime(beforeDate(40));
        query.setEndTime(beforeDate(20));
        PageRecord<PipelineInstance> record = pipelineInstanceDomainService.pageByPipelineCode(1L, 50L, query);
        List<PipelineInstance> records = record.getRecords();
        records.forEach(pipelineInstance -> {
            redisHelper.enqueue(Constant.WAIT_RUNNING_PIPELINE_QUEUE_KEY, pipelineInstance.getInstanceCode());
        });

    }

    public Date beforeDate(Integer minute) {
        Calendar calendar = Calendar.getInstance();
        /* HOUR_OF_DAY 指示一天中的小时 */
        calendar.setTime(new Date());
        // 减去3分钟
        calendar.add(Calendar.MINUTE, -minute);
        return calendar.getTime();
    }


}
